import axios from "axios";
import {ElMessage,ElMessageBox } from "element-plus";
import errorCode from "./errorCode.js";

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout:5000,
    // 携带Cookie
    // withCredentials: true
})
/*request.interceptors.request.use(
config =>{
    const token = window.localStorage.getItem("token")
    if(token){
        config.headers.common['Authorization'] = 'Bearer ' + token
        return config
    }
},
ereror =>Promise.reject(ereror)
)*/
// 是否显示重新登录
export let isRelogin = { show: false };

// http request 拦截器
request.interceptors.request.use(
    config => {
        if (localStorage.token) { //判断token是否存在
            config.headers.token  = window.localStorage.getItem('token');  //将token设置成请求头
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
request.interceptors.response.use(res => {
        const code = res.data.code || 200;
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        if (code === 401) {
            if (!isRelogin.show) {
                isRelogin.show = false
                window.localStorage.removeItem("token")
                location.href = '/login';
                ElMessage.warning('登录状态已过期，请重新登录！')
            }
            return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
        } else if (code === 500) {
            ElMessage({ message: msg, type: 'error' })
            return Promise.reject(new Error(msg))
        }else if (code === 601) {
            ElMessage({ message: msg, type: 'warning' })
            return Promise.reject('error')
        } else if (code !== 200) {
            ElMessage.error(msg)
            Notification.error({ title: msg })
            return Promise.reject('error')
        } else {
            return res.data
        }

    },
    error => {
        return Promise.reject(error);
    }
)


export default request
